import React from "react";
import SearchHeader from "./component/SearchHeader";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import "../style/style.less";
import ThePagination from "../../../components/ThePagination";
import { apiGetCommodityList, apiProductInfoPutaway, apiProductInfoDel, apiUpdateInventory } from '@/request/commodity'
import TheImage from '@/components/TheImage'
import TheDialog from '@/components/TheDialog'
import SkuChange from './component/SkuDetailsChange'
import _ from 'lodash'
import { exportSheetTable } from '@/utils/exportTable'

class List extends React.Component {
  state = {
    columns: [
      {
        title: "商品ID",
        dataIndex: "productId",
        key: "productId",
      },
      {
        title: "商品名称",
        dataIndex: "productName",
        key: "productName",
      },
      {
        title: "商品图片",
        dataIndex: "productShowImages",
        key: "productShowImages",
        render: (text, record) => {
          return <TheImage src={record.productShowImages.split(',')[0]} width={80} height={80} />
        }
      },
      {
        title: "所属类目",
        dataIndex: "productClassifyName",
        key: "productClassifyName",
      },
      {
        title: "商品原价",
        dataIndex: "originalPrice",
        key: "originalPrice",
        render: (text, record) => {
          return <React.$Price price={record.originalPrice || 0} />
        }
      },
      {
        title: "商品现价",
        dataIndex: "currentPrice",
        key: "currentPrice",
        render: (text, record) => {
          return <React.$Price price={record.currentPrice || 0} />
        }
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
      },
      {
        title: "申请时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "上次操作时间",
        dataIndex: "lastUpdateTime",
        key: "lastUpdateTime",
        render: (text, record) => {
          return record.lastUpdateTime ? record.lastUpdateTime : "/"
        }
      },
      {
        title: "操作人",
        dataIndex: "userName",
        key: "userName",
        render: (text, record) => {
          return record.userName ? record.userName : "/"
        }
      },
      {
        title: "状态",
        dataIndex: "productStatus",
        key: "productStatus",
        render: (text, render) => {
          let label = ''
          switch (render.productStatus) {
            case 'Y':
              label = "上架"
              break;
            case 'N':
              label = "下架"
              break;
            case 'G':
              label = '管理员下架'
              break;
            default:
              label = "字段值错误"
          }
          return label
        }
      },
      {
        title: "操作",
        fixed: "right",
        width: 300,
        render: (text, render) => {
          return (
            <div>
              <TheButton hasPermi={['commodity:list:detail']} onClick={() => this.goDetail(render.productId)}>商品详情</TheButton>
              <TheButton hasPermi={['commodity:list:edit']} onClick={() => this.goEdit(render.productId)}>修改商品</TheButton>
              <TheButton hasPermi={['commodity:list:evaluate']} onClick={() => this.goEvaluate(render.productId, render.storeName)}>商品评价</TheButton>
              {/* <TheButton hasPermi={['commodity:list:delete']} onClick={() => this.delConfirm(render.productId)}>删除商品</TheButton> */}
              {(render.productStatus === 'N' && render.productStatus !== 'G') && <TheButton hasPermi={['commodity:list:onShelf']} onClick={() => this.putShelf(render.productId, 'Y')}>上架</TheButton>}
              {render.productStatus === 'Y' && <TheButton hasPermi={['commodity:list:onShelf']} onClick={() => this.offShelf(render.productId, 'N')}>下架</TheButton>}
              {/* <TheButton hasPermi={['commodity:list:updateStock']} onClick={() => this.openSkuDialog(render.productId)}>修改库存</TheButton> */}
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    searchValue: {},
    loading: false
  };
  async componentDidMount() {
    if (localStorage.getItem('searchValue') && localStorage.getItem('pageNo')) {
      let search = JSON.parse(localStorage.getItem('searchValue'))
      this.setState({
        searchValue: search,
        pageData: {
          pageNo: localStorage.getItem('pageNo'),
          pageSize: 10
        }
      }, async () => {
        await this.getData()
      })
    } else if (localStorage.getItem('pageNo')) {
      this.setState({
        pageData: {
          pageNo: localStorage.getItem('pageNo'),
          pageSize: 10
        }
      }, async () => {
        await this.getData()
      })
    } else {
      await this.getData()
    }
  }
  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let res = await apiGetCommodityList({ ...pageData, ...searchValue, reviewStatus: 'T' })
    if (res.code === 0 && res.data) {
      this.setState({ dataSource: res.data, pageData: { pageNo: res.pageNo, pageSize: res.pageSize }, total: res.totalCount, loading: false })
    }
  }
  getValue = (value) => {
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => {
      this.getData()
      let search = JSON.stringify(this.state.searchValue)
      localStorage.setItem('searchValue', search)
      localStorage.setItem('pageNo', this.state.pageData.pageNo)
    })
  }
  goDetail = (productId) => {
    this.props.history.push(`/commodity/list/detail/${productId}`);
  };
  goEvaluate = (productId, storeName) => {
    this.props.history.push(`/commodity/list/evaluate/${productId}/${encodeURIComponent(storeName)}`);
  };
  goEdit = productId => {
    this.props.history.push(`/commodity/list/edit/${productId}`);
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      localStorage.setItem('pageNo', this.state.pageData.pageNo);
      this.getData()
    })
  };
  delConfirm = (productId) => {
    React.$confirm({
      title: "您确认删除此条商品吗?",
      onOk: async () => {
        let res = await apiProductInfoDel({ productId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      },
    });
  };
  offShelf = (productId, productStatus) => {
    React.$confirm({
      title: '您确定下架该商品吗？',
      onOk: async () => {
        await apiProductInfoPutaway({ productId, productStatus })
        await this.getData()
      }
    })
  }
  putShelf = (productId, productStatus) => {
    React.$confirm({
      title: '您确定上架该商品吗？',
      onOk: async () => {
        await apiProductInfoPutaway({ productId, productStatus })
        await this.getData()
      }
    })
  }
  openSkuDialog = (skuProductId) => {
    this.setState({
      skuVisible: true,
      skuProductId
    })
  }
  closeSkuDialog = () => {
    this.setState({
      skuVisible: false,
      skuProductId: ''
    })
  }
  getSkuProperty = (skuPropertyArray, skuPropertyTable, skuType) => {
    let arr = [];
    if (skuPropertyTable.length > 0) {
      if (
        Object.prototype.toString.call(skuPropertyTable[0]) ===
        "[object Object]"
      ) {
        skuPropertyTable.forEach((v) => {
          arr.push(v);
        });
        arr = [arr];
      } else {
        arr = skuPropertyTable;
      }
    }
    this.setState({ skuPropertyArray, skuPropertyTable: arr, skuType });
  };
  /**
   * @desc 获取sku价格返回值
   * */
  getNumResult = (numResult) => {
    this.setState({ numResult });
  };
  handleOk = () => {
    const { numResult } = this.state
    let stockArr = numResult.map(v => {
      return {
        productSkuId: v.SKUId,
        skuStock: v.stock
      }
    })
    this.updateStock(stockArr)
  }
  updateStock = async stockArr => {
    let res = await apiUpdateInventory([...stockArr])
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改成功'
      })
      this.closeSkuDialog()
    }
  }
  //表格导出
  async toExportTable() {
    const { searchValue } = this.state
    this.setState({ down_loading: true })
    await React.$post('/management/productInfo/exportProductDetail', { ...searchValue, reviewStatus: 'T' }).then(res => {
      if (res.code === 0 && res.data.length >= 0) {
        let tH_data = [
          { prop: 'productName', title: '商品名称' },
          { prop: 'productId', title: '商品Id' },
          { prop: 'sku', title: 'sku名称' },
          { prop: 'materialId', title: '物料id' },
          // { prop: 'price', title: '成本价', valueType: 'number' },
          { prop: 'productSkuId', title: 'productSkuId' },
          { prop: 'skuOriginalPrice', title: 'sku原价', valueType: 'number' },
          { prop: 'skuCurrentPrice', title: 'sku现价', valueType: 'number' },
          { prop: 'createTime', title: '商品创建时间' },
          { prop: 'goodsStatus', title: '商品上下架' },
          { prop: 'putawayTime', title: '上架时间' },
          { prop: 'skuStatus', title: '规格上下架' },
          { prop: 'skuStock', title: '库存', valueType: 'number' }
        ],
          isSheet = true,
          fileName = '商品列表',
          tB_data = []
        res.data.forEach(item => {
          tB_data.push({
            productName: item.productName,
            productId: item.productId,
            sku: item.sku,
            materialId: item.materialId,
            // price: item.price ? (item.price / 100).toFixed(2) : '/',
            productSkuId: item.productSkuId,
            skuOriginalPrice: item.skuOriginalPrice,
            skuCurrentPrice: item.skuCurrentPrice,
            createTime: item.createTime,
            goodsStatus: item.goodsStatus,
            putawayTime: item.putawayTime,
            skuStatus: item.skuStatus,
            skuStock: item.skuStock,
          })
        })
        this.setState({ down_loading: false })
        exportSheetTable({ fileName, tH_data, tB_data, isSheet })

      } else {
        React.$message({
          type: 'warning',
          content: '导出操作失败,请重试'
        })
        this.setState({ down_loading: false })
      }
    }).catch(err => {
      React.$message({
        type: 'warning',
        content: '导出操作失败,请重试'
      })
      this.setState({ down_loading: false })

    })
  }
  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      loading,
      skuVisible,
      skuProductId
    } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        <SearchHeader toAdd={() => this.props.history.push('/commodity/list/add')} history={this.props.history} getValue={this.getValue} toExport={() => this.toExportTable()} />
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={dataSource}
            loading={loading}
          />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
        <TheDialog
          width={800}
          title={'修改库存'}
          visible={skuVisible}
          handleCancel={this.closeSkuDialog}
          handleOk={this.handleOk}
        >
          <SkuChange id={skuProductId} getNumResult={this.getNumResult} getSkuProperty={this.getSkuProperty} />
        </TheDialog>
      </div>
    );
  }
}

export default List;
